﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;

namespace ClockSync
{
    public class NeighbourTable
    {
        private List<Neighbour> neighbours;
        private string neighbourAsString;

        public string NeighbourAsString
        {
            get
            {
                neighbourAsString = this.serialize();
                return this.serialize();
            }
        }

        public List<Neighbour> Neighbours
        {
            get
            {
                return this.neighbours;
            }
        }

        public NeighbourTable()
        {
            neighbours = new List<Neighbour>();
        }

        public NeighbourTable(byte[] byteIps)
        {
            neighbours = new List<Neighbour>();
            //get the neibours from tcp byte string delimited by ';'
            string temp = System.Text.ASCIIEncoding.ASCII.GetString(byteIps);
            temp=temp.Substring(0,temp.LastIndexOf(';'));
            //split by the ';' delimiter
            string[] ips = temp.Split(';');

            foreach (string s in ips)
            {
                string[] ipAndPort = s.Split(':');
                int port = Convert.ToInt32(ipAndPort[1]);
                IPAddress addr = IPAddress.Parse(ipAndPort[0]);
                Neighbour n = new Neighbour(addr, port);
                neighbours.Add(n);
            }

        }

        public void addNeighbour(string addr)
        {
            Neighbour n = new Neighbour(IPAddress.Parse(addr), 8001);
            neighbours.Add(n);
        }

        public string serialize()
        {
            string _NeighbourAsString = "";
            foreach (Neighbour n in neighbours)
            {
                _NeighbourAsString+=n.Address + ":" + n.Port +";";
            }
            return _NeighbourAsString;
        }

        public Neighbour getMaster()
        {
            foreach (Neighbour n in neighbours)
            {
                if (n.IsMaster)
                {
                    return n;
                }
            }

            return null;
            

        }


    }
}
